# -*- coding: utf-8 -*-
#
# Copyright © 2010 Benedikt Eger
#
# This file is part of top-news-buzz.
#
# top-news-buzz is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# top-news-buzz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with top-news-buzz.  If not, see <http://www.gnu.org/licenses/>.

import logging
import os

from topnewsbuzz.config import Config, MetricConfigEntry

class MetricBase(object):

    def __init__(self):
        self.config = []

        enabled_config = MetricConfigEntry('enabled', 'True', 'Enable metric', 'The metric is only applied if enabled', MetricConfigEntry.INPUT_TYPE_RADIO, self)
        self.enabled = True if enabled_config.value == 'True' else False
        self.config.append(enabled_config)

        boost_config = MetricConfigEntry('boost', '1.0', 'Metric boost', 'Metric evaluation is multiplied by this value', MetricConfigEntry.INPUT_TYPE_TEXT, self)
        try:
            self.boost = float(boost_config.value)
        except ValueError:
            self.boost = 1.0
        self.config.append(boost_config)

    def display_name(self):
        if hasattr(self, 'name'):
            return self.name
        else:
            return self.__module__

class MetricHelper:

    @staticmethod
    def load_metrics():
        metric_list = []

        for f in os.listdir(os.path.abspath(os.path.dirname(__file__))):
            module_name, ext = os.path.splitext(f) # Handles no-extension files, etc.
            if ext == '.py': # Important, ignore .pyc/other files.
                module_name = 'topnewsbuzz.metrics.' + module_name
                metrics = __import__(module_name).metrics

        for metric_name in dir(metrics):
            if not metric_name.startswith('__'):
                metric_module = getattr(metrics, metric_name)
                if hasattr(metric_module, 'Metric'):
                    metric = metric_module.Metric()
                    metric_list.append(metric)
                    logging.debug('Metric loaded: %s' % metric.__module__)

        return metric_list
